#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2021/12/4 17:22'
# software: PyCharm

import random
import time

from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt


from apps.app01 import models
from apps.app01.forms.wiki import WikiModelForm
from utils.encrypt import uid
from utils.upload_file import upload_image


def wiki(request):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, "wiki.html")
    wiki_object = models.Wiki.objects.filter(pk=wiki_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request):
    """
    wiki添加
    :param request:
    :return:
    """
    if request.method == "GET":
        form = WikiModelForm(request)
        return render(request, "wiki_form.html", {"form": form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("wiki")
    return render(request, 'wiki_form.html', {'form': form})


def wiki_edit(request, wiki_id):
    """
    编辑
    :param request:
    :return:
    """
    wiki_object = models.Wiki.objects.filter(pk=wiki_id).first()
    if not wiki_object:
        url = reversed("wiki")
        return redirect(url)
    if request.method == "GET":
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        form.save()
        url = reverse("wiki")
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)


def delete_wiki(request, wiki_id):
    """
    删除wiki
    :param request:
    :param wiki_id:
    :return:
    """
    models.Wiki.objects.filter(id=wiki_id).delete()

    return redirect("wiki")


def wiki_catalog(request):
    wiki_data = models.Wiki.objects.all().values("id", "title", "project_id").order_by("pk")
    return JsonResponse({'status': True, "wiki_data": list(wiki_data)})


@csrf_exempt
def wiki_upload(request):
    """
    markdown插件上传图片
    :param request:
    :param project_id:
    :return:
    """
    result = {
        'success': 0,
        'message': None,
        'url': None,
        'status_code': None
    }
    image_object = request.FILES.get('editormd-image-file')
    ext = image_object.name.rsplit('.')[-1]
    str_time = time.time()
    str_random = "{0}{1}".format(str_time, random.randrange(999999))
    key = "{0}.{1}".format(uid(str_random), ext)
    image_url = upload_image(request, image_object, key)
    result["success"] = 1
    result["url"] = image_url
    return JsonResponse(result)
